package com.znufe.exam.third.votesdk.impl;

import com.znufe.exam.base.BaseConstant;
import com.znufe.exam.domain.*;
import com.znufe.exam.domain.enums.ExamPaperAnswerStatusEnum;
import com.znufe.exam.domain.other.ExamPaperAnswerUpdate;
import com.znufe.exam.repository.ExamPaperMapper;
import com.znufe.exam.repository.QuestionMapper;
import com.znufe.exam.service.*;
import com.znufe.exam.service.impl.ExamPaperAnswerServiceImpl;
import com.znufe.exam.third.votesdk.JChoicesCallback;
import com.znufe.exam.utility.ExamUtil;
import com.znufe.exam.utility.VoteUtil;
import com.znufe.exam.viewmodel.student.exam.ExamPaperSubmitItemVM;
import com.znufe.exam.viewmodel.vote.VoteVM;
import io.undertow.util.QValueParser;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: 08-uexam
 * @Package: com.znufe.exam.third.votesdkController
 * @ClassName: JChoices
 * @Author: bot
 * @Description:
 * @Date: 2020/6/15 21:26
 * @Version: 1.0
 */
@Data
@Component
public class JChoices implements JChoicesCallback {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private static JChoices jChoices;
    @Autowired
    public RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public StudentService studentService;

    @Autowired
    public QuestionMapper questionMapper;

    @Autowired
    public ExamPaperMapper examPaperMapper;

    @Autowired
    public ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService;

    @Autowired
    public ExamPaperAnswerService examPaperAnswerService;

    @Autowired
    public ClassInteractionCustomerAnswerService classInteractionCustomerAnswerService;

    @PostConstruct
    public void init() {
        jChoices = this;
        jChoices.redisTemplate = this.redisTemplate;
        jChoices.studentService = this.studentService;
        jChoices.examPaperAnswerService = this.examPaperAnswerService;
        jChoices.questionMapper = this.questionMapper;
        jChoices.examPaperMapper = this.examPaperMapper;
        jChoices.examPaperQuestionCustomerAnswerService = this.examPaperQuestionCustomerAnswerService;
        jChoices.classInteractionCustomerAnswerService = this.classInteractionCustomerAnswerService;
    }

    /**
     * 通过签题器选择，查询缓存获取到当前正在考试的题目信息
     * 直接插入到t_exam_paper_question_customer_answer表
     *
     * @param BasementID
     * @param KeyID
     * @param Value
     * @param KeyTime
     * @return
     */
    @Override
    public int invoke(short BasementID, short KeyID, short Value, float KeyTime) {
        logger.info("JChoices invoke is begin ");
        logger.info("BasementID is:" + BasementID + "; KeyID is:" + KeyID + "; Value is:" + Value + "; KeyTime is:" + KeyTime);

        VoteVM voteVM = (VoteVM) jChoices.redisTemplate.opsForValue().get(BaseConstant.VOTE);
        logger.info("voteVM is: " + voteVM.toString());
        logger.info("questionId is: " + voteVM.getQuestionEditRequestVM().getId() + "; getExamId is: " + voteVM.getExamId());
        logger.info("classId is: " + voteVM.getClassId() + "; questionType is: " + voteVM.getQuestionEditRequestVM().getQuestionType());

        String answer = VoteUtil.intToAnswer(Value);
        Question question = jChoices.questionMapper.selectByPrimaryKey(voteVM.getQuestionEditRequestVM().getId());
        //处理答题器接收到的答案信息
        ExamPaperSubmitItemVM customerQuestionAnswer = new ExamPaperSubmitItemVM();
        if (question.getQuestionType().equals(BaseConstant.SingleChoice) ) {
            //单选题或判断题
            customerQuestionAnswer.setContent(answer);
        } else if (question.getQuestionType().equals(BaseConstant.MultipleChoice)) {
            //如果是多选题
            if (answer != "") {
                customerQuestionAnswer.setContentArray(Arrays.asList(answer.split(",")));
            }
        } else if (question.getQuestionType().equals(BaseConstant.TrueFalse)) {
            //判断题
            if(Value == 64 ){
                customerQuestionAnswer.setContent("A");
                answer = "A";
            }else {
                customerQuestionAnswer.setContent("B");
                answer = "B";
            }

        }

        if(voteVM.getExamType() == BaseConstant.EXAM_TYPE_OFFICAL){
            //写入到t_exam_paper_question_customer_answer表进行答案录入和成绩计算；
            logger.info("JChoices invoke EXAM_TYPE_OFFICAL is: EXAM_TYPE_OFFICAL" );
            //TODO 有个问题需要解决，如果是重复提交，就会插入多条记录，如何规避这个问题，在此处将班级ID插入到user.setId，
            //写入到t_exam_paper_question_customer_answer表create_user字段。
            //此设计的依据是：一个班级对于一套试卷，只会考一次，不会考两次或多次，
            // 另外，如果有学生是多次提交，t_exam_paper_question_customer_answer表会存在多条记录，取答题结果是只能取最后一条
            //通过question_id、create_user、exam_paper_id、subject_id、vote_base_id分组 按itemorder 倒排序取最后一条便为答题记录；
            //itemOrder字段是答题器回调函数生成的，该值越大，表示答题时间越长；


            ExamPaper examPaper = jChoices.examPaperMapper.selectByPrimaryKey(voteVM.getExamId());
            examPaper.setVoteBaseId((int) BasementID);
            examPaper.setSubjectId((int) KeyID);
            User user = new User();
            user.setId(voteVM.getClassId());
            ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = jChoices.examPaperAnswerService.ExamPaperQuestionCustomerAnswerFromVM(question, customerQuestionAnswer, examPaper, (int) KeyTime, user, new Date());
            //todo存入数据库
            List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswerList = new ArrayList<>();
            examPaperQuestionCustomerAnswerList.add(examPaperQuestionCustomerAnswer);
            jChoices.examPaperQuestionCustomerAnswerService.insertList(examPaperQuestionCustomerAnswerList);
        }else if(voteVM.getExamType() == BaseConstant.EXAM_TYPE_INTERACT){
            logger.info("JChoices invoke EXAM_TYPE_OFFICAL is: EXAM_TYPE_INTERACT" );
            ClassInteractionCustomerAnswer classInteractionCustomerAnswer = new ClassInteractionCustomerAnswer();
            //classID复用试卷ID
            classInteractionCustomerAnswer.setClassId(voteVM.getExamId());
            classInteractionCustomerAnswer.setCourseId(voteVM.getCourseId());
            classInteractionCustomerAnswer.setExamPaperType(BaseConstant.EXAM_TYPE_INTERACT);
            classInteractionCustomerAnswer.setQuestionId(voteVM.getQuestionEditRequestVM().getId());
            classInteractionCustomerAnswer.setVoteBaseId((int) BasementID);
            classInteractionCustomerAnswer.setVoteId((int) KeyID);
            classInteractionCustomerAnswer.setAnswerId(answer);
            jChoices.classInteractionCustomerAnswerService.insertSelective(classInteractionCustomerAnswer);

        }



        logger.info("JChoices invoke is end ");
        return 0;
    }


    /**
     * 原有业务逻辑，通过答题器ID、基站ID反查到学生信息，后续业务流程变更，不需要学生信息ID
     * @param BasementID
     * @param KeyID
     * @param Value
     * @param KeyTime
     * @return

     @Override public int invoke(short BasementID, short KeyID, short Value, float KeyTime) {
     logger.info("JChoices invoke is begin ");
     logger.info("BasementID is:" + BasementID + "; KeyID is:" + KeyID + "; Value is:" + Value+ "; KeyTime is:" + KeyTime);
     VoteVM voteVM = (VoteVM) jChoices.redisTemplate.opsForValue().get(BaseConstant.VOTE);
     logger.info("questionId is: " + voteVM.getQuestionEditRequestVM().getId() + "; getExamId is: " + voteVM.getExamId());
     logger.info("classId is: " + voteVM.getClassId() + "; questionType is: " + voteVM.getQuestionEditRequestVM().getQuestionType());

     //根据classId, keyID获取到学生ID，解析value值，获取到当前题目的答案；
     Student student = new Student();
     student.setVoteId((int) KeyID);
     student.setClassId(voteVM.getClassId());
     List<Student> studentList = jChoices.studentService.queryStudentList(student);
     //有且查询到一条记录，同一个班级,voteId唯一
     if(studentList != null && studentList.size() == 1){
     student = studentList.get(0);
     logger.info("JChoices invoke student is:" + student.toString());
     //写入到t_exam_paper_question_customer_answer表进行答案录入和成绩计算；
     //处理答题器接收到的答案信息
     String answer = VoteUtil.intToAnswer(Value);
     Question question =  jChoices.questionMapper.selectByPrimaryKey(voteVM.getQuestionEditRequestVM().getId());

     ExamPaperSubmitItemVM customerQuestionAnswer = new ExamPaperSubmitItemVM();
     if(question.getQuestionType().equals(BaseConstant.SingleChoice) || question.getQuestionType().equals(BaseConstant.TrueFalse)){
     //单选题或判断题
     customerQuestionAnswer.setContent(answer);
     }else if(question.getQuestionType().equals(BaseConstant.MultipleChoice) ){
     //如果是多选题
     if(answer != "" ){
     customerQuestionAnswer.setContentArray(Arrays.asList(answer.split(",")));
     }
     }

     ExamPaper examPaper =  jChoices.examPaperMapper.selectByPrimaryKey(voteVM.getExamId());
     examPaper.setVoteBaseId((int) BasementID);
     examPaper.setSubjectId((int) KeyID);
     User user = new User();
     user.setId(student.getId());
     ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = jChoices.examPaperAnswerService.ExamPaperQuestionCustomerAnswerFromVM(question, customerQuestionAnswer, examPaper, (int) KeyTime, user, new Date());
     //todo存入数据库
     List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswerList = new ArrayList<>();
     examPaperQuestionCustomerAnswerList.add(examPaperQuestionCustomerAnswer);
     jChoices.examPaperQuestionCustomerAnswerService.insertList(examPaperQuestionCustomerAnswerList);


     }else{
     logger.error("JChoices invoke is fail, find no student " + student.toString());
     }

     logger.info("JChoices invoke is end ");
     return 0;
     } */
}
